#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
unordered_map<int, int> mp;
class Solution {
public:

    TreeNode* mybuilt(vector<int>& preorder, vector<int>& postorder, int prel, int prer, int posl, int posr) {
        if (prel > prer || posl > posr)return nullptr;
        if (prel == prer)return new TreeNode(preorder[prel]);
        int root_pre = prel;
        int root_next = mp[preorder[prel + 1]];
        TreeNode* root = new TreeNode(preorder[prel]);
        int lsz = root_next - posl + 1;
        root->left = mybuilt(preorder, postorder, prel + 1, prel + lsz, posl, posl + lsz - 1);
        root->right = mybuilt(preorder, postorder, prel + lsz + 1, prer, posl + lsz, posr);
        return root;
    }
    TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) {
        int n = preorder.size();
        for (int i = 0; i < n; i++) {
            mp[postorder[i]] = i;
        }
        return mybuilt(preorder, postorder, 0, n - 1, 0, n - 1);
    }
};